//
//  HomeTableViewController.m
//  BaseFrameworkOC
//
//  Created by Vicent on 2021/9/6.
//

#import "HomeTableViewController.h"
#import "NetworkingTool.h"
#import "HomeModel.h"
#import "HomeTableViewCell.h"
#import "HomeViewModel.h"

static NSString * const kCellId = @"HomeTableViewCell";

@interface HomeTableViewController ()

@property (nonatomic, strong) HomeModel *model;
@property (nonatomic, strong) HomeViewModel *vm;

@end

@implementation HomeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self.tableView registerClass:UITableViewCell.class forCellReuseIdentifier:kCellId];
    UINib *nib =  [UINib nibWithNibName:kCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kCellId];
    
    HomeRequestBean *requestBean = [HomeRequestBean new];
    requestBean.page = 0;
    requestBean.pageCount = 10;
    NSDictionary *param = requestBean.mj_keyValues;
    NSLog(@"请求参数%@",param);
    
    [self.vm requestHomeList:param successBlock:^(NSDictionary * _Nonnull responseDic) {
        self.model = [HomeModel mj_objectWithKeyValues:responseDic];
        if (self.model.list.count) {
            [self.vm parseModelToVM:self.model];
            [self.tableView reloadData];
        }
        NSLog(@"vm is %@",self.vm);
    } failedBlock:^(NSError * _Nonnull error) {
        NSLog(@"请求出错,错误信息为%@",error);
    }];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.vm.cellVMList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeTableViewCell *cell = (HomeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:kCellId forIndexPath:indexPath];
    cell.vm = self.vm.cellVMList[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeTableViewCell *cell = (HomeTableViewCell *)[NSBundle.mainBundle loadNibNamed:@"HomeTableViewCell" owner:nil options:nil].firstObject;
    return [cell rowHeightWithModel:self.vm.cellVMList[indexPath.row]];
}

- (HomeViewModel *)vm {
    if (_vm == nil) {
        _vm = [[HomeViewModel alloc] init];
    }
    return _vm;
}

@end
